import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, loginState, removeToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { resetRouter } from '@/router'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/a/detail'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // 修改跳转时的title
  if (to.query.route_title) {
    to.meta.title = to.query.route_title
  }

  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  const timeState = loginState();

  if (hasToken && timeState) {
    store.commit('isKeepAlive', from.path);
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // 动态路由
      const hasPers = store.getters.permission_routes.length > 0;
      if (hasPers) {
        // 判断跳转路由是否存在
        console.log(store.state.isEventTriggered, "isEventTriggeredisEventTriggeredisEventTriggeredisEventTriggered", to.path)
        let pathVal = to.path;
        if (to.path.indexOf('/redirect') != -1) {
          pathVal = to.path.replace('/redirect', '');
        }
        // console.log(pathVal, "要去的地方")
        // console.log(store.getters.allPath, "所有的路由")
        if (store.getters.allPath.indexOf(pathVal) == -1) {
          // 不存在就提示
          if (store.state.isEventTriggered) {
            store.commit('isEventTriggeredFunc', false);
            Message.warning("您没有权限访问该页面");
            NProgress.done();
            return;
          }
          Message.warning("您没有权限访问该页面或地址错误，即将跳转首页~");
          next(`/login`)
          NProgress.done();
          return;

        }

        // 判断进入页面是否已被缓存(进入同个页面携带不同参数就刷新页面)
        //  && JSON.stringify(to.query) != '{}'
        if (store.getters.visitedViews.length != 0) {
          let index = store.getters.visitedViews.findIndex((item) => {
            // 判断是存在缓存的路由并且参数不同，刷新页面
            return item.path == to.path && JSON.stringify(item.query) != JSON.stringify(to.query);
          });
          // 不存在直接进入页面
          if (index == -1) {
            next()
            return;
          }
          // 删除缓存，重新加载页面
          store.dispatch("tagsView/delView", store.getters.visitedViews[index]).then((res) => {
            console.log(res, "删除页面tab");
            next()
          });
        } else {
          next()
        }
      } else {
        store.dispatch("user/getOrganizationDetails", {});//获取字段权限
        try {
          const accessRoutes = await store.dispatch('permission/generateRoutes');
          // console.log(accessRoutes, '---------------')
          router.addRoutes(accessRoutes);
          next({ ...to, replace: true })
        } catch (error) {
          console.log(error)
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          // Message.error(error || 'Has Error')
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    removeToken();

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
